package com.example.gokuplayalong.bases.exception;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.network.updown.Upload;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.kongzue.dialogx.dialogs.PopTip;

import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;

import okhttp3.MediaType;

public class ExceptionUtils {
    /**
     * 获取当前程序行数，类名，方法名
     *
     * @return 行数，类名，方法名
     */
    public static String getTraceInfo() {
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stacks = new Throwable().getStackTrace();
        int stacksLen = stacks.length;
        sb.append("; number: ")
                .append(stacks[1].getLineNumber())
                .append("class: ")
                .append(stacks[1].getClassName())
                .append("; method: ")
                .append(stacks[1].getMethodName());
        return sb.toString();
    }

    public static void getException(String cml, Throwable e) {
        try {
            File f = new File(AppParams.getInstance().mediaDir, "error.log");
            if (!f.exists()) {
                f.createNewFile();
            }

            if (f.length() > 1 * 1024 * 1024) {
                if (f.delete()) f.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(f.getAbsoluteFile(), true);
            fileWriter.write(cml + "\n");
            fileWriter.write(Tools.getSDF().format(System.currentTimeMillis()));
            fileWriter.write(e.getMessage());
            fileWriter.write(Arrays.toString(e.getStackTrace()));
            fileWriter.write("\n\n");
            fileWriter.close();


            Upload.getInstance()
                    .uploadFile(MediaType.parse("text/plain"), "error.log", Tools.getUUID() + ".txt", new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(@NonNull Message msg) {
                            super.handleMessage(msg);
                            switch (msg.what) {
                                case 1: {
                                    Logger.d("上传错误日志成功");
                                }
                                break;
                                case 2: {
                                    Logger.d("上传错误日志失败");
                                }
                                break;
                            }
                        }
                    });


        } catch (Exception ex) {

        }
    }
}
